<template>
	<view class="wrap">
		<u-form class="form" :model="model" :rules="rules" ref="uForm" :label-position="labelPosition">
			<u-form-item label="群类型" prop="natureType" label-width="180" :required="true">
				<js-select v-model="model.natureType" :items="natureTypeOptions" itemLabel="label"
					itemValue="value" placeholder="请选择群类型" :disabled="disabled"></js-select>
			</u-form-item>
			<u-form-item label="群名称" prop="name" label-width="180" :required="true">
				<u-input placeholder="请输入群名称" v-model="model.name" type="text" maxlength="64" style="text-align: left;"
					:disabled="disabled"></u-input>
			</u-form-item>
			<u-form-item label="群主" prop="ownerName" label-width="180" :required="true">
				<u-input v-model="model.ownerName" :type="disabled?'text':'select'" placeholder="请选择群主" :disabled="disabled" @click="chooseGroupOwner"></u-input>
				<js-choose-user-popup v-if="useInitChooseUserComp" ref="chooseGroupOwner" @submit="useGroupOwnerSelected"
					:mode="popupGroupOwner.mode" :multiple="popupGroupOwner.multiple"
					:action="chooseUserUrl" :default-selected-user-list = "defaultGroupOwnerUserList"></js-choose-user-popup>
			</u-form-item>
			<u-form-item ref="uFormItemUserList" label="群成员" prop="userList" label-width="180" label-position="top" :required="true">
				<view>
					<scroll-view :scroll-top="scrollTop" :scroll-y="scrollY" :class="{'scroll-Y': isScroll}"
						@scroll="scroll">
						<u-tag :text="item.name" :type="uTagProps.type" v-for="(item, index) in model.userList" 
							:key="item.userId" :index="item.userId" :shape="uTagProps.shape" 
							:closeable="uTagProps.closeable" :mode="uTagProps.mode" 
							:size="uTagProps.size" @close="doDeleteUser" class="uTagStyle"></u-tag>
					</scroll-view>
				</view>
				<u-button v-if="!isViewMode" slot="right" type="success" size="mini" @click="chooseGroupUsers" style="">选择成员</u-button>
				<js-choose-user-popup v-if="useInitChooseUserComp" ref="chooseGroupUsers" @submit="useGroupUsersSelected"
					:mode="popupGroupUsers.mode" :multiple="popupGroupUsers.multiple"
					:action="chooseUserUrl" :default-selected-user-list = "defaultGroupMemberUserList"></js-choose-user-popup>
			</u-form-item>
			<u-form-item label="回收策略" prop="revokeStrategy" label-width="180" :required="true">
				<js-select v-model="model.revokeStrategy" :items="revokeStrategyOptions" itemLabel="label"
					itemValue="value" placeholder="请选择回收策略" :disabled="disabled"></js-select>
			</u-form-item>
			<u-form-item v-if="showRevokeTime" label="回收时间" prop="revokeTime" label-width="180" :required="true">
				<view style="width: 100%;">
					<u-input v-model="model.revokeTime == ''?'请选择时间':model.revokeTime" :type="disabled?'input':'select'" @click="uPicker.show = !disabled" :disabled="disabled"></u-input>
					<u-picker v-model="uPicker.show" :mode="uPicker.mode" :params="uPicker.params" @confirm="confirm"></u-picker>
				</view>
			</u-form-item>
			<u-form-item label="欢迎语" prop="wecomeMsg" label-width="180" label-position="top">
				<u-input type="textarea" placeholder="请输入短信内容" v-model="model.wecomeMsg" height="100" maxlength="500" :disabled="disabled"/>
			</u-form-item>
		</u-form>
		<view style="display: flex;flex-direction: row;">
			<u-button v-if="!isViewMode" class="btn" style="width: 50%;margin-right: 10rpx;" type="primary" @click="submit">保存</u-button>
			<u-button class="btn" style="width: 50%;" @click="cancel">
				{{isViewMode ? '返回' : '取消'}}
			</u-button>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				model: {
					id: '',
					natureType: '',
					name: '',
					owner: '',
					ownerName: '',
					userList: [],
					revokeStrategy: '',
					revokeTime: '',
					wecomeMsg: ''
				},
				natureTypeOptions: [],
				revokeStrategyOptions: [],
				// 是否不展示教学的群类型及对应的课程结束后半年回收的策略
				isHideTeachNatureType: true,
				isModelLoadedFlag: false,
				// 操作模式：view、add、edit
				mode: '',
				uPicker: {
					show: false,
					mode: 'time',
					params: {
						year: true,
						month: true,
						day: true,
						hour: true,
						minute: true,
						second: true
					},
				},
				uTagProps: {
					mode: 'light',
					type: 'primary',
					size: 'default',
					shape: 'square',
					closeable: true
				},
				isViewMode: false,
				showRevokeTime: false,
				labelPosition: 'left',
				disabled: true,
				rules: {
					natureType: [{
						required: true,
						message: '请选择群类型',
						trigger: 'change',
					}],
					name: [{
						required: true,
						message: '请输入群名称',
						trigger: 'blur',
					}],
					ownerName: [{
						required: true,
						message: '请选择群主',
						trigger: 'change',
					}],
					userList: [{
						required: true,
						message: '请选择群成员',
						trigger: 'change',
						type: 'array'
					}, {
						validator: (rule, value, callback) => {
							let validateResult = value.some((user) => user.userId == this.model.owner);
							return validateResult;
						},
						message: '群主必须在群成员内',
						trigger: 'change'
					}],
					revokeStrategy: [{
						required: true,
						message: '请选择回收策略',
						trigger: 'change',
					}],
					revokeTime: [{
						validator: (rule, value, callback) => {
							let validateResult = true;
							if (this.model.revokeStrategy == "1" && !this.model.revokeTime) {
								validateResult = false;
							}
							return validateResult;
						},
						message: '请选择回收时间',
						trigger: 'change',
					}],
					wecomeMsg: [{
						required: true,
						message: '请输入欢迎语',
						trigger: ['change', 'blur'],
					}]
				},
				labelPosition: 'left',
				chooseUserUrl: '/api/blade-system/user/user-list-by-dept-type',
				popupGroupOwner: {
					show: false,
					mode: "bottom",
					multiple: false,
				},
				popupGroupUsers: {
					show: false,
					mode: "bottom",
					multiple: true,
				},
				isScroll: true,
				scrollTop: 0,
				scrollY: true,
				old: {
					scrollTop: 0
				}
			};
		},
		computed: {
			/**
			 * 返回是否初始化选择用户组件的标识
			 * 解决父组件将请求回来的数据传递给子组件的延迟问题
			 */
			useInitChooseUserComp: function(){
				let useInit = false;
				if(this.mode === 'add' || (this.mode === 'edit' && this.isModelLoadedFlag)){
					useInit = true;
				}
				return useInit;
			},
			defaultGroupOwnerUserList: function(){
				let userList = [];
				if(this.model.owner){
					userList.push({
						id: this.model.owner,
						name: this.model.ownerName
					});
				}
				return userList;
			},
			defaultGroupMemberUserList: function(){
				let userList = this.model.userList.map(user => {
					return {
						id: user.userId,
						name: user.name,
					}
				});
				return userList;
			}
		},
		watch: {
			'model.revokeStrategy': function(val, oldVal) {
				if (val == "1") {
					this.showRevokeTime = true;
				} else {
					this.showRevokeTime = false;
				}
			},
			'model.userList': function(val,oldVal){
				// 触发u-form-item(uFormItemUserList)组件实例的on-form-change事件
				this.$refs.uFormItemUserList.$emit('on-form-change', val);
			}
		},
		onLoad(params) {
			// console.log("1.onLoad...");
			this.initWechatNatureType();
			this.initRevokeStrategy();
			this.initData(params);
		},
		created() {
			// console.log("2.created...");
		},
		onReady() {
			// console.log("3.onReady...");
			this.$refs.uForm.setRules(this.rules);
		},
		mounted(){
			// console.log("4.mounted...");
		},
		methods: {
			initWechatNatureType() {
				this.$u.api.dictBizData({
					code: "wechat_nature_type"
				}).then(res => {
					let optionList = [];
					res.data.forEach((item) => {
						if(this.isHideTeachNatureType && item.dictKey == '2'){
							return;
						}
						optionList.push({
							'label': item.dictValue,
							'value': item.dictKey
						});
					})
					this.natureTypeOptions = optionList;
				});
			},
			initRevokeStrategy() {
				this.$u.api.dictBizData({
					code: "wechat_revoke_strategy"
				}).then(res => {
					let optionList = [];
					res.data.forEach((item) => {
						if(this.isHideTeachNatureType && item.dictKey == '2'){
							return;
						}
						optionList.push({
							'label': item.dictValue,
							'value': item.dictKey
						});
					})
					this.revokeStrategyOptions = optionList;
				});
			},
			initData(params){
				let vm = this;
				this.mode = params.mode;
				if (params.id) {
					if (this.mode == "view") {
						this.disabled = true;
						this.isViewMode = true;
						this.uTagProps.closeable = false;
					} else {
						this.disabled = false;
						this.isViewMode = false;
						this.uTagProps.closeable = true;
					}
					this.$u.api.wechat.wechatGroup.detail({
						id: params.id
					}).then(res => {
						Object.assign(vm.model, res.data);
						vm.model.natureType = res.data.natureType.toString();
						vm.model.revokeStrategy = res.data.revokeStrategy.toString();
						vm.model.status = res.data.status.toString();
						vm.isModelLoadedFlag = true;
					});
				} else {
					this.disabled = false;
				}
			},
			confirm(e) {
				this.model.revokeTime = '';
				let params = this.uPicker.params;
				if (params.year) {
					this.model.revokeTime += e.year;
				}
				if (params.month) {
					this.model.revokeTime += '-' + e.month;
				}
				if (params.day) {
					this.model.revokeTime += '-' + e.day;
				}
				if (params.hour) {
					this.model.revokeTime += ' ' + e.hour;
				}
				if (params.minute) {
					this.model.revokeTime += ':' + e.minute;
				}
				if (params.second) {
					this.model.revokeTime += ':' + e.second;
				}
				this.uPicker.show = false;
			},
			chooseGroupOwner() {
				if(this.disabled){
					return;
				}
				this.$refs.chooseGroupOwner.open();
				this.$refs.chooseGroupOwner.setDefaultSelectedUserList(this.defaultGroupOwnerUserList);
			},
			useGroupOwnerSelected() {
				let groupOwnerArr = this.$refs.chooseGroupOwner.getData();
				if (groupOwnerArr.length > 0) {
					let groupOwner = groupOwnerArr[0];
					this.model.owner = groupOwner.id;
					this.model.ownerName = groupOwner.name;
				}
				this.$refs.chooseGroupOwner.close();
			},
			chooseGroupUsers() {
				this.$refs.chooseGroupUsers.open();
				this.$refs.chooseGroupUsers.setDefaultSelectedUserList(this.defaultGroupMemberUserList);
			},
			useGroupUsersSelected() {
				let groupUsers = this.$refs.chooseGroupUsers.getData();
				if (groupUsers.length > 0) {
					this.model.userList = [];
				}
				groupUsers.forEach((element) => {
					this.model.userList.push({
						"name": element.name,
						"userId": element.id
					});
				});
				this.$refs.chooseGroupUsers.close();
			},
			scroll: function(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
			doDeleteUser: function(userId) {
				this.model.userList = this.model.userList.filter(user => userId != user.userId);
				// this.$refs.chooseGroupUsers.doUnSelectDataById(userId);
				this.$refs.chooseGroupUsers.$emit('remove-selected-user-by-id',userId);
			},
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						uni.showLoading({
							title: '提交中....'
						})
						this.$u.api.wechat.wechatGroup.save(this.model).then(res => {
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: res.msg,
								showCancel: false,
								success: function() {
									if (res.code == 200) {
										uni.setStorageSync('refreshWecahtGroupList', true);
										uni.navigateBack();
									}
								}
							});
						});
					} else {
						this.$u.toast('您填写的信息有误，请根据提示修正。');
					}
				});
			},
			cancel() {
				uni.navigateBack();
			}
		}
	};
</script>
<style lang="scss" scoped>
	.wrap {
		padding: 30rpx;
	}

	.uTagStyle {
		margin-right: 10rpx;
	}

	.scroll-Y {
		height: 200rpx;
	}

	/deep/ ::-webkit-scrollbar {
		/*滚动条整体样式*/
		width: 4px !important;
		height: 1px !important;
		overflow: auto !important;
		background: #ccc !important;
		-webkit-appearance: auto !important;
		display: block;
	}

	/deep/ ::-webkit-scrollbar-thumb {
		/*滚动条里面小方块*/
		border-radius: 10px !important;
		box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2) !important;
		background: #7b7979 !important;
	}

	/deep/ ::-webkit-scrollbar-track {
		/*滚动条里面轨道*/
		background: #FFFFFF !important;
	}
</style>